﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EyeGuard
{
	public partial class MainForm : Form
	{
		private bool disableFlag;
		private Timer notifyTimer;
		private Timer forceRelaxTimer;
		private static string[] disableBtnTextes = { "暂停", "恢复" };
        private int forceRelaxSec = 20;

        private int WorkingMinute
		{
			get { return Properties.Settings.Default.workingTime; }
		}
		private int WorkingMilliSeconds
		{
			get { return WorkingMinute * 60 * 1000; }
		}

		private int RelaxMinute
		{
			get { return Properties.Settings.Default.relaxTime; }
		}
		private int RelaxMilliSeconds
		{
			get { return RelaxMinute * 60 * 1000; }
		}

		private int DailyLimitHour
		{
			get { return Properties.Settings.Default.dailyLimitTime; }
		}

		private int DelayRelaxMinute
		{
			get { return Properties.Settings.Default.delayRelaxTime; }
		}
		private int DelayRelaxMilliSeconds
		{
			get { return DelayRelaxMinute * 60 * 1000; }
		}
		private bool ForceRestFlag
		{
			get { return Properties.Settings.Default.forceRestFlag; }
		}

		public MainForm()
		{
			InitializeComponent();
		}

		private void MainForm_Load(object sender, EventArgs e)
		{
			disableFlag = false;
			SetDisableBtnText();
			SetToggleMenuItemText();

			// start the notify timer
			notifyTimer = new Timer();
			notifyTimer.Tick += new EventHandler(TimerEventProcessor);
			EnableNotifyTimer(WorkingMilliSeconds);

            forceRelaxTimer = new Timer();
            forceRelaxTimer.Tick += new EventHandler(ForceRelaxEventProcessor);
            forceRelaxTimer.Interval = forceRelaxSec * 1000;
            forceRelaxTimer.Enabled = false;
        }

		private void SetDisableBtnText()
		{
			DisableButton.Text = GetDisableBtnText();
		}

		private void SetToggleMenuItemText()
		{
			MenuItem_Toggle.Text = GetDisableBtnText();
		}

		private string GetDisableBtnText()
		{
			var idx = Convert.ToInt16(disableFlag);
			return disableBtnTextes[idx];
		}

		private void SettingButton_Click(object sender, EventArgs e)
		{
			using (var settingForm = new SettingForm() { StartPosition = FormStartPosition.CenterParent })
			{
				settingForm.ShowDialog(this);
				settingForm.Close();
			}
		}

		private void RelaxButton_Click(object sender, EventArgs e)
		{
			if (MessageBox.Show("立即休息？", "休息",
				MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				RelaxRightNow();
			}
		}

		private void AboutButton_Click(object sender, EventArgs e)
		{
			using (var aboutForm = new AboutForm { StartPosition = FormStartPosition.CenterParent })
			{
				aboutForm.ShowDialog(this);
				aboutForm.Close();
			}
		}

		private void DisableButton_Click(object sender, EventArgs e)
		{
			var disableBtnText = GetDisableBtnText();
			if (MessageBox.Show($"确定要{disableBtnText}？", "切换",
				MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				ToggleDisableBtn();
			}
		}

		private void EnableNotifyTimer(int interval)
		{
			notifyTimer.Interval = interval;
			notifyTimer.Enabled = true;
		}

		private void DisableNotifyTimer()
		{
			notifyTimer.Stop();
            forceRelaxTimer.Stop();
		}

		private void ToggleDisableBtn()
		{
			disableFlag = !disableFlag;
			SetDisableBtnText();
			SetToggleMenuItemText();
			ToggleIcon();

			if (disableFlag)
			{
				DisableNotifyTimer();
			}
			else
			{
				EnableNotifyTimer(WorkingMilliSeconds);
			}
		}

		private void ToggleIcon()
		{
			if (disableFlag)
			{
				this.EyeGuardIcon.Icon = Properties.Resources.EyeGuard_gray;
			} else
			{
				this.EyeGuardIcon.Icon = Properties.Resources.EyeGuard_normal;
			}
		}

		private void TimerEventProcessor(object sender, EventArgs e)
		{
			DisableNotifyTimer();

			if (disableFlag)
			{
				return;
			}

			if (ForceRestFlag) {
				RelaxRightNow();
			} else {
				using (var dummyForm = new Form() { TopMost = true })
				{
					forceRelaxTimer.Start();

					if (MessageBox.Show(dummyForm, $"{forceRelaxSec}秒后自动休息？\n\r（是）我知道了；（否）延后{DelayRelaxMinute * 60}秒", "休息提示",
						MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
					{
						if (forceRelaxTimer.Enabled)
						{
							EnableNotifyTimer(DelayRelaxMilliSeconds);
							forceRelaxTimer.Stop();
						}
					}
				}
			}
		}

		private void ForceRelaxEventProcessor(object sender, EventArgs e)
        {
            forceRelaxTimer.Stop();

            IntPtr ptr = NativeMethods.FindWindow(null, "休息提示");
            if (ptr != IntPtr.Zero)
            {
                IntPtr result;
                NativeMethods.EndDialog(ptr, out result);
            }
            RelaxRightNow();
        }

        private void RelaxRightNow()
		{
			DisableNotifyTimer();
			ShowNotifyForm();
			EnableNotifyTimer(WorkingMilliSeconds + RelaxMilliSeconds);
		}

		private void ShowNotifyForm()
		{
			var screens = Screen.AllScreens;
			foreach (var screen in screens)
			{
				var notifyForm = new NotifyForm(screen);
				notifyForm.Show(this);
			}
		}

		private void ShowMainForm()
		{
			this.Visible = true;
			this.ShowInTaskbar = true;
			this.WindowState = FormWindowState.Normal;
		}

		private void HideMainForm()
		{
			this.Hide();
			this.ShowInTaskbar = false;
			this.WindowState = FormWindowState.Minimized;
			this.EyeGuardIcon.Visible = true;
		}

		private void EyeGuardIcon_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			ShowMainForm();
		}

		private void MenuItem_Hide_Click(object sender, EventArgs e)
		{
			HideMainForm();
		}

		private void MenuItem_Show_Click(object sender, EventArgs e)
		{
			ShowMainForm();
		}

		private void MenuItem_Quit_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void MenuItem_Relax_Click(object sender, EventArgs e)
		{
			RelaxButton_Click(sender, e);
		}

		private void MenuItem_Toggle_Click(object sender, EventArgs e)
		{
			DisableButton_Click(sender, e);
		}

		private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (this.WindowState != FormWindowState.Minimized)
			{
				e.Cancel = true;
				HideMainForm();
			}
		}

        internal static class NativeMethods
        {
            [System.Runtime.InteropServices.DllImport("user32.dll")]
            internal static extern bool EndDialog(IntPtr hDlg, out IntPtr nResult);
            [DllImport("user32.dll", SetLastError = true)]
            internal static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        }
    }
}
